<template>
  <div class="page-container" :loading="state.loading">
    <div class="app-container top-info">
      <h3
        >名称 <el-input class="tip" v-model.trim="formModel.machineName" maxLength="12" /> [编号：{{
          data?.machineSn
        }}] &nbsp;&nbsp;监控设备序列号: <el-input class="tip" v-model.trim="formModel.serialNumber"
      /></h3>
      <div class="justify-space-between top-center">
        <el-descriptions>
          <el-descriptions-item label="型号:">
            <el-input disabled v-model="formModel.machineModel" />
          </el-descriptions-item>
          <el-descriptions-item label="备注:">
            <el-input class="tip" v-model="formModel.remark" maxLength="250" />
          </el-descriptions-item>
          <el-descriptions-item label="销售额:"> {{ data.salesAmount }}元 </el-descriptions-item>

          <el-descriptions-item label="维修负责人:">
            <ApiSelect
              :clearable="false"
              v-model="formModel.serviceContracts"
              :api="selectState.user.api"
              :params="{
                ...selectState.user.roleParams.repair,
                companyId: formModel.companyId,
                cityName
              }"
              :valueField="selectState.user.valueField"
              :labelField="selectState.user.labelField"
              :immediate="true"
              @change="contractChange"
            />
          </el-descriptions-item>
          <el-descriptions-item label="维修负责人电话:">
            <el-input v-model="formModel.servicePhone" disabled />
          </el-descriptions-item>
          <el-descriptions-item label="阈值:">
            <el-input-number
              style="width: 120px"
              v-model="formModel.threshold"
              :min="1"
              controls-position="right"
            />
          </el-descriptions-item>
          <el-descriptions-item label="创建人:">
            {{ data?.createOper }}
          </el-descriptions-item>

          <el-descriptions-item label="创建时间:">
            {{ data?.createTime }}
          </el-descriptions-item>

          <el-descriptions-item label="设备类型:">
            <el-select disabled v-model="formModel.machineType" placeholder="请选择" filterable>
              <el-option
                v-for="dict in device_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-descriptions-item>
        </el-descriptions>

        <div class="right-block justify-space-around">
          <div>
            设备状态<br />
            <span class="stat">{{ data?.enable ? '启用中' : '禁用' }}</span>
          </div>
          <div>
            <div>网络状态</div>
            <div class="stat">
              <span :class="data?.onlineStatus ? 'net-ball-on' : 'net-ball-off'"></span>
              {{ data?.onlineStatus ? '在线' : '离线' }}
            </div>
          </div>
        </div>
      </div>
      <el-menu default-active="1" mode="horizontal" @select="onMenuChange">
        <el-menu-item index="1">基本信息</el-menu-item>
        <el-menu-item index="2">货道信息</el-menu-item>
      </el-menu>
      <el-button class="top-btn" type="primary" @click="handleRestart">重启设备</el-button>
    </div>

    <div class="device-content app-container">
      <!-- 設備信息 -->
      <div v-show="state.activeIndex == 1" class="deivce-info">
        <div class="white-bg app-container">
          <el-descriptions class="device-position" title="投放信息" :column="4">
            <el-descriptions-item label="公司名称:">
              <ApiSelect
                style="width: 200px"
                v-model="formModel.companyId"
                :options="companyOptions"
                valueField="companyId"
                labelField="name"
                :immediate="true"
                disabled
              />
            </el-descriptions-item>
            <el-descriptions-item label="区域名称:">
              <ApiSelect
                :clearable="false"
                v-model="formModel.areaId"
                :api="selectState.area.api"
                :params="{ companyId: formModel.companyId, enable: 1 }"
                :valueField="selectState.area.valueField"
                :labelField="selectState.area.labelField"
                :immediate="true"
              />
            </el-descriptions-item>
            <el-descriptions-item label="线路名称:">
              <ApiSelect
                :clearable="false"
                v-model="formModel.routeId"
                :api="selectState.route.api"
                :params="{ areaId: formModel.areaId, enable: 1 }"
                :valueField="selectState.route.valueField"
                :labelField="selectState.route.labelField"
                :immediate="true"
              />
            </el-descriptions-item>
            <el-descriptions-item label="点位名称:">
              <ApiSelect
                v-if="positionOptions.length > 0"
                :clearable="false"
                v-model="formModel.positionId"
                :api="selectState.point.api"
                :params="{ routeId: formModel.routeId, enable: 1 }"
                :valueField="selectState.point.valueField"
                :labelField="selectState.point.labelField"
                :immediate="true"
                :isDevicePosition="true"
                @change="routeChange"
              />
              <ApiSelect
                v-else
                :clearable="false"
                v-model="formModel.positionName"
                :api="selectState.point.api"
                :options="positionOptions"
                :params="{ routeId: formModel.routeId, enable: 1 }"
                :valueField="selectState.point.valueField"
                :labelField="selectState.point.labelField"
                :immediate="true"
                :isDevicePosition="true"
                @change="routeChange"
              />
            </el-descriptions-item>
            <el-descriptions-item label="点位类型:">
              <el-input style="width: 200px" v-model="formModel.positionTypeName" disabled />
            </el-descriptions-item>
            <el-descriptions-item label="支付方式:">
              <el-select multiple v-model="formModel.payment" filterable>
                <el-option
                  v-for="dict in sys_paytype"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-descriptions-item>
            <el-descriptions-item label="投放地址:">
              <MapInput
                v-model:value="formModel.positionAddr"
                v-model:lng="formModel.longitude"
                v-model:lat="formModel.latitude"
              />
            </el-descriptions-item>
            <el-descriptions-item label="设备标签:">
              <ApiSelect
                :clearable="false"
                v-model="formModel.machineTagId"
                :api="selectState.tag.api"
                :params="selectState.tag.params"
                :valueField="selectState.tag.valueField"
                :labelField="selectState.tag.labelField"
                :resultField="selectState.tag.resultField"
                :immediate="true"
              />
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="white-bg app-container">
          <el-descriptions title="设备检测">
            <el-descriptions-item label="温度:">{{ data?.temperature }}°C</el-descriptions-item>
            <el-descriptions-item label="开关门检测:">
              <dict-tag class="dict-tag" :options="device_status" :value="data?.openDoorCheck" />
            </el-descriptions-item>
            <el-descriptions-item label="关门检测:">
              <dict-tag class="dict-tag" :options="device_status" :value="data?.closeDoorCheck" />
            </el-descriptions-item>
            <el-descriptions-item label="出餐检测:">
              <dict-tag class="dict-tag" :options="device_status" :value="data?.outMealCheck" />
            </el-descriptions-item>
            <el-descriptions-item label="取餐检测:">
              <dict-tag class="dict-tag" :options="device_status" :value="data?.takeMealCheck" />
            </el-descriptions-item>
            <el-descriptions-item label="离线时长:">
              {{ data?.offlineDuration ?? 0 }}
            </el-descriptions-item>
            <el-descriptions-item label="运营状态:">
              <dict-tag
                class="dict-tag"
                :options="device_sale_status"
                :value="data?.operationStatus"
              />
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div class="white-bg app-container">
          <el-descriptions title="系统信息">
            <el-descriptions-item label="固件版本:">
              {{ data?.firmwareVersion }}
            </el-descriptions-item>
            <el-descriptions-item label="当前设备软件版本号:">
              {{ data?.appVersion }}
            </el-descriptions-item>
          </el-descriptions>
          <h5>App列表</h5>
          <div class="indent-block">
            <ApkVList :machineType="formModel.machineType" :machineId="state.machineId" />
          </div>
          <h5>业务信息</h5>
          <div class="indent-block">
            <DeviceAd :machineId="state.machineId" />
          </div>
        </div>

        <div class="white-bg app-container">
          <el-descriptions class="device-status" title="设备状态" :column="4">
            <el-descriptions-item label="VMC连接状态:">
              <dict-tag class="dict-tag" :options="device_status" :value="data?.vmcStatus" />
            </el-descriptions-item>
            <el-descriptions-item label="售卖状态:">
              <dict-tag
                class="dict-tag"
                :options="device_sale_status"
                :value="data?.operationStatus"
              />
            </el-descriptions-item>
          </el-descriptions>
          <div class="indent-block">
            <h5>故障信息</h5>
            <el-button class="download-btn" type="primary" plain link @click="handleLog">
              设备日志下载
            </el-button>
          </div>
          <div class="indent-block">
            <DeviceErrorLogs :machineId="state.machineId" />
          </div>
        </div>

        <div class="flex-center white-bg app-container">
          <el-button @click="handleAction(false)">取消</el-button>
          <el-button
            type="primary"
            v-hasPermi="['machine:machine:edit']"
            @click="handleAction(true)"
          >
            确定
          </el-button>
        </div>
      </div>

      <!-- 貨道信息 -->
      <div v-if="state.activeIndex == 2" class="goods-info">
        <GoodsList :machineId="state.machineId" :machineType="formModel.machineType" />

        <div class="flex-center white-bg app-container">
          <el-button @click="handleAction(false)">关闭</el-button>
        </div>
      </div>
    </div>

    <DownloadLog ref="logRef" :machineId="state.machineId" />
  </div>
</template>

<script setup name="DeviceDetail">
import { useOrganApiConfig } from '@/hooks/service'
import useUserStore from '@/store/modules/user'
import { getDeviceDetail, updateDevice, restartDevice } from '@/api/device'
import ApkVList from './components/ApkVList'
import DeviceAd from './components/DeviceAd'
import DeviceErrorLogs from './components/DeviceErrorLogs'
import DownloadLog from './components/DownloadLog'
import GoodsList from './components/GoodsList'
import { ElMessageBox } from 'element-plus'
import { getPointByRouteId } from '@/api/organization/common'

const userStore = useUserStore()
const route = useRoute()
const { proxy } = getCurrentInstance()
const companyOptions = computed(() => userStore.companys)
const selectState = useOrganApiConfig()
const { sys_paytype, device_type, device_status, device_sale_status } = proxy.useDict(
  'sys_paytype',
  'device_type',
  'device_status',
  'device_sale_status'
)
const modelObj = {
  companyId: null,
  machineId: null,
  machineModel: null,
  describe: null,
  serviceContracts: null,
  servicePhone: null,
  comboTotal: null,
  machineType: null,
  areaId: null,
  routeId: null,
  positionId: null,
  positionTypeName: null,
  payType: null,
  positionAddr: null,
  longitude: null,
  latitude: null,
  machineTagId: null,
  remark: null,
  threshold: null,
  machineName: null,
  serialNumber: null
}
const formModel = ref(modelObj)
const logRef = ref()
const data = ref({})
const state = reactive({
  loading: false,
  activeIndex: 1,
  machineId: ''
})

const onMenuChange = (val) => (state.activeIndex = val)
const handleLog = () => logRef.value?.init()
const routeChange = (_, val) => (formModel.value.positionTypeName = val?.typeName)
const contractChange = (_, val) => (formModel.value.servicePhone = val?.phonenumber)

function handleAction(confirm) {
  if (confirm) {
    if (!formModel.value.machineModel) {
      return proxy.$modal.msgError('设备型号不能为空')
    } else if (!formModel.value.payment.length) {
      return proxy.$modal.msgError('支付方式不能为空')
    }

    ElMessageBox.confirm('确认要修改该设备数据吗？', '系统提示', {
      type: 'warning'
    }).then(() => {
      const { createTime, operationTime, payment, ...data } = formModel.value
      updateDevice(data).then(() => {
        proxy.$modal.msgSuccess('更新成功')
        setTimeout(proxy.$tab.closeOpenPage({ path: '/device/deviceManage' }), 1000)
      })
    })
  } else {
    proxy.$tab.closeOpenPage({ path: '/device/deviceManage' })
  }
}

const positionOptions = ref([])
function handleRestart() {
  restartDevice(state.machineId).then((r) => {
    proxy.$modal.msgSuccess('已发送重启设备指令')
  })
}

const cityName = ref('')
onMounted(async () => {
  const id = route.query.id
  if (!id) return
  state.machineId = id
  state.loading = true
  try {
    const r = await getDeviceDetail(id)
    data.value = r?.data ?? {}

    Object.keys(modelObj).map((k) => {
      formModel.value[k] = data.value[k] ?? ''
    })
    formModel.value['serviceContracts'] = +data.value?.serviceContracts || ''

    const { payType, machineType } = data.value

    if (payType === 0) {
      formModel.value.payment = ['1', '2']
    } else {
      formModel.value.payment = payType ? [`${payType}`] : []
    }
    formModel.value.machineType = machineType ? `${machineType}` : ''
    formModel.value.positionName = data.value?.positionName || ''
    let name = data?.value?.areaName?.split('/')[0]
    cityName.value = name || ''
    console.log('area', cityName)
    const res = await getPointByRouteId({ routeId: formModel.value.routeId, enable: 1 })
    positionOptions.value = res?.data || []
  } finally {
    state.loading = false
  }
})
</script>

<style lang="scss" scoped>
.dict-tag {
  display: inline-block;
}
.page-container {
  min-width: 900px;
  background-color: var(--el-bg-color-page);
  overflow-x: scroll;
}
:deep(.el-descriptions__header) {
  border-bottom: 1px solid var(--el-color-info-light-7);
  margin-bottom: 10px;
  padding-bottom: 6px;
}
.top-info {
  position: relative;
  background: var(--el-bg-color);
  padding-bottom: 0;
  .el-input,
  .el-select {
    max-width: 120px;
  }
  .tip {
    max-width: 200px;
    width: 200px;
  }
  .top-center {
    .el-descriptions {
      flex: 6;
      max-width: 800px;
    }
    .right-block {
      flex: 3;
      max-width: 300px;
      // min-width: 300px;
      color: var(--el-color-info);
      font-size: 16px;
      align-items: center;
      text-align: center;
      > div {
        margin: 20px;
      }
      .stat {
        color: black;
        font-size: 18px;
        line-height: 3em;
      }
    }
  }
  .top-btn {
    position: absolute;
    right: 20px;
    bottom: 5px;
  }
}

.device-content {
  background-color: var(--el-bg-color-page);
  .app-container {
    background-color: var(--el-bg-color);
    margin-bottom: 20px;
  }
  .el-descriptions {
    :deep(.el-descriptions__body) {
      width: 900px;
    }
  }
  .device-position {
    :deep(.el-descriptions__body) {
      width: 100%;
    }
  }
  .indent-block {
    width: 800px;
    position: relative;
    > div {
      margin-left: 2em;
    }
  }
  .device-status {
    :deep(.el-descriptions__body) {
      width: 500px;
    }
  }
  .download-btn {
    position: absolute;
    right: 0;
    top: 0;
  }
}
</style>
